今天要介紹的是如何在MVC的前端View當中利用Ajax將值傳遞到後端Controller,這邊示範的是利用Ajax將Aras連線資訊送往後端進行Aras連線的處理,想了解Aras連線的朋友可以看 (https://ithelp.ithome.com.tw/articles/10215186) 的介紹
View
- 首先在前端View當中利用jQuery的$(document).ready將這個function在頁面資訊載入後就自動執行,下方再加入Ajax並利用POST的方式將要傳送的路徑依照Action/Controller的方式加入url中,最後在將要傳送的資料寫成JSON的格式加入data當中
<script type="text/javascript">
$(document).ready(function () {
let urlParams = new URLSearchParams(window.location.search);
var Url= urlParams.get('url');
var User_Name = urlParams.get('user_name');
var User_Password = urlParams.get('user_password');
var Db_Name = urlParams.get('db_name');
var DCO_ID = urlParams.get('DCO_id');
$.ajax({
url: '@Url.Action("Index", "CAD")',
type: 'POST',
data: { url: Url, user_name: User_Name, user_password:
User_Password, db_name:Db_Name, DCO_id: DCO_ID}
});
})();
</script>
Controller
- 後端的部分先宣告連線資訊為static的全域變數,之後再Action當中利用Request.Form來接收前端Ajax傳送過來的登入資訊並且存進static全域變數當中
public static string select_url; //定義Connection的url
public static string select_user_name; //定義Connection的user_name
public static string select_user_password; //定義Connection的user_password
public static string select_db_name; //定義Connection的db_name
public static string DCO_ID;
public ActionResult Index()
{
//接收前端ajax傳送過來的item_type與Aras登入的URL,帳號,密碼,資料庫名稱
select_url = Request.Form["url"];
select_user_name = Request.Form["user_name"];
select_user_password = Request.Form["user_password"];
select_db_name = Request.Form["db_name"];
DCO_ID = Request.Form["DCO_id"];
return View();
}
- 這麼一來就可以在任何一個Action當中將連線資訊利用建構子的方式寫入連線的Class當中
Connection con = new Connection();
Innovator inn = con.Connect(select_url, select_user_name,select_user_password, select_db_name);
- 最後進入到連線的Class當中完成與Aras的連線就可以使用IOM了
public class Connection
{
//藉由前端收的資料,建立與Aras之間的連線(抓當前登入Aras的資料)
public Innovator Connect(string select_url, string select_user_name,string
select_user_password, string select_db_name)
{
Innovator inn;
string url = select_url;
string db = select_db_name;
string user = select_user_name;
string pw = select_user_password;
HttpServerConnection cnx = IomFactory.CreateHttpServerConnection(url,
db, user, pw);
Item login_result = cnx.Login();
inn = IomFactory.CreateInnovator(cnx);
return inn;
}
}